<script lang="ts" setup>
import { addCardAPI, editCardAPI, getCardDetailAPI } from '@/apis/card';
import router from '@/router';
import type { AddCardParams } from '@/types/card';
import { validateCarNumber } from '@/utils/validate';
import { ElMessage, type FormInstance } from 'element-plus';
import { computed, onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';


// 车辆信息数据
const carInfo = ref<AddCardParams>({
  personName: '', // 车主姓名
  phoneNumber: '', // 联系方式
  carNumber: '', // 车辆号码
  carBrand: '', // 车辆品牌
})
// 车辆信息校验规则
const carInfoRules = {
  personName: [
    { required: true, message: '请输入车主姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '长度为11个字符', trigger: 'blur' }
  ],
  carNumber: [
    { required: true, message: '请输入车辆号码', trigger: 'blur' },
    // 自定义校验
    { validator: validateCarNumber, trigger: 'blur'  }
  ],
  carBrand: [
    { required: true, message: '请输入车辆品牌', trigger: 'blur' },
    { min: 2, max: 8, message: '车辆品牌在 2 到 8 个字符', trigger: 'blur' }
  ]
}

// 支付方式
const payMethod = [
  {
    label: '微信支付',
    value: 'WeChat'
  },
  {
    label: '支付宝',
    value: 'AliPay'
  },
  {
    label: '线下',
    value: 'Cash'
  }
]

// 缴费信息
const feeInfo = ref({
  paymentAmount: '', // 支付金额
  paymentMethod: '', // 支付方式
  payTime: ['', ''], // 支付时间 (包括开始 和 结束)
  rechargeId: -1 // 充值id
})

// 缴费信息校验规则
const feeInfoRules = {
  paymentAmount: [
    { required: true, message: '请输入支付金额', trigger: 'blur' },
    // 严谨来讲 只能是数字 \d 添加正则表达式 
    { pattern: /^[1-9]\d*$/, message: '请输入正确的支付金额', trigger: 'blur' }
  ],
  paymentMethod: [ 
    { required: true, message: '请选择支付方式', trigger: 'blur' }
  ],
  payTime: [
    { required: true, message: '请选择支付时间', trigger: 'blur' }
  ]
}
const carInfoRef = ref<FormInstance>()
const feeInfoRef = ref<FormInstance>()

// 获取月卡的id
const route = useRoute()
const id = computed(() => {
  return route.query.id as string
})

onMounted(() => {
  if (id.value)  {
    // 编辑月卡 -> 回显表单
    getCardDetail()
  }
})

const getCardDetail = async() => {
  // 发送请求 -> 获取月卡详情
  const res = await getCardDetailAPI(id.value)
  console.log(res.data)

  // 回显车辆信息
  const { carInfoId,  carBrand, personName, phoneNumber, carNumber } = res.data 
  carInfo.value = {
    carBrand,
    personName,
    phoneNumber,
    carNumber,
    carInfoId  // 车辆id -> 为了编辑月卡时使用
  }

  // 回显缴费信息
  const { rechargeId,  paymentAmount, paymentMethod, cardStartDate, cardEndDate } = res.data
  feeInfo.value = {
    paymentAmount: paymentAmount!,
    payTime: [cardStartDate!, cardEndDate!],
    paymentMethod: paymentMethod!,
    rechargeId: rechargeId! // 充值id
  }
}


// 确定提交
const confirm = async() => {
  // 分别针对于表单进行整体的校验
  await carInfoRef.value!.validate()
  await feeInfoRef.value!.validate()
  console.log('通过校验')
  // 组合数据
  const addPayload = { 
    ...carInfo.value, // 车辆信息
    paymentAmount: feeInfo.value.paymentAmount, // 支付金额
    paymentMethod: feeInfo.value.paymentMethod,
    cardStartDate: feeInfo.value.payTime[0], // 开始时间
    cardEndDate: feeInfo.value.payTime[1], // 结束时间
    // rechargeId: feeInfo.value.rechargeId // 充值id
   } as AddCardParams
  // 提交请求
  // 区分新增和编辑
  if (id.value)  {
    // 编辑月卡
    addPayload.rechargeId = feeInfo.value.rechargeId
    await editCardAPI(addPayload)
  } else {
    // 新增月卡
    await addCardAPI(addPayload)
  }
  // 提示用户
  ElMessage.success( id.value ? '编辑月卡成功'  : '添加月卡成功')
  // 返回到上一页
  router.back()
}
// 重置
const cancel = async () => {
  await carInfoRef.value!.resetFields()
  await feeInfoRef.value!.resetFields()
}
</script>

<template>
  <div class="add-card">
    <header class="add-header">
      <el-page-header :content="id ?  '编辑月卡' : '增加月卡'" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">车辆信息</div>
        <div class="form">
          <el-form ref="carInfoRef" :rules="carInfoRules"  :model="carInfo" label-width="100px">
            <el-form-item prop="personName" label="车主姓名">
              <el-input v-model="carInfo.personName" />
            </el-form-item>
            <el-form-item  prop="phoneNumber" label="联系方式">
              <el-input   v-model="carInfo.phoneNumber" />
            </el-form-item>
            <el-form-item prop="carNumber"  label="车辆号码">
              <el-input v-model="carInfo.carNumber" />
            </el-form-item>
            <el-form-item prop="carBrand" label="车辆品牌">
              <el-input v-model="carInfo.carBrand" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-container">
        <div class="title">最新一次月卡缴费信息</div>
        <div class="form">
          <el-form ref="feeInfoRef" :rules="feeInfoRules" :model="feeInfo" label-width="100px">
            <el-form-item prop="payTime" label="有效日期">
              <!-- [ '2025-06-5', '2025-06-7' ] -->
              <el-date-picker v-model="feeInfo.payTime" value-format="YYYY-MM-DD" type="daterange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期" />
            </el-form-item>
            <el-form-item  prop="paymentAmount" label="支付金额">
              <el-input v-model="feeInfo.paymentAmount" />
            </el-form-item>
            <el-form-item  prop="paymentMethod" label="支付方式">
              <el-select v-model="feeInfo.paymentMethod">
                <el-option v-for="item in payMethod" :key="item.label" :value="item.value" :label="item.label" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>

    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="cancel">重置</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </footer>
  </div>
</template>



<style scoped lang="scss">
.add-card {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }

    .preview {
      img {
        width: 100px;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>